<?php

class ValidateField {
    public static function validateField($field, $value, $user=null) {
        switch ($field) {
            case "name":
                if (empty($value) || !is_string($value) || strlen($value) < 3 || strlen($value) > 50) {
                    return false;
                } else {
                    return true;
                }
            case "surname":
                if (empty($value) || !is_string($value) || (strlen($value) < 3 || strlen($value) > 50)) {
                    return false;
                } else {
                    return true;
                }

            case "username":
                if (empty($value) || !is_string($value) || (strlen($value) < 3 || strlen($value) > 50)) {
                    return false;
                } else {
                    return true;
                }
            case "username_free":

                $sql = "SELECT count(*) as num_username from user where username = ?";

                $stmt = DB::getDBO()->prepare($sql);
                $stmt->execute(array($value));


                $result = $stmt->fetch();
                if ($result['num_username'] != 0)
                    return false;
                else
                    return true;
            case "email":
                if (!preg_match('/^[^\W][a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*\@[a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*\.[a-zA-Z]{2,4}$/', $value) OR $value == "") {
                    return false;
                } else {
                    return true;
                }
            case "emailFree":
                $sql = "SELECT count(*) as num_email from user where email = ?";

                $stmt = DB::getDBO()->prepare($sql);
                $stmt->execute(array($value));


                $result = $stmt->fetch();
                if ($result['num_email'] != 0)
                    return false;
                else
                    return true;
            case "password":
                if ($value == "") {
                    return false;
                } else {
                    return true;
                }

            case "oldpw":
                $sql = "select count(*) as nr_res from user where password = md5(?) and username = ?";

                $stmt = DB::getDBO()->prepare($sql);
                $stmt->execute(array($value,$user->getUsername()));


                $result = $stmt->fetch();
                if ($result['nr_res'] != 0)
                    return false;
                else
                    return true;
        }
    }
}
?>
